package com.cat.binaryTree;

import java.awt.datatransfer.FlavorListener;
import java.util.*;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/description/
 * @create 2025/9/23 20:25
 * @since JDK17
 */

public class Solution59 {
    public int minimumOperations(TreeNode root) {
        Deque<TreeNode> q = new ArrayDeque<>();
        q.add(root);
        int ans = 0;
        while (!q.isEmpty()) {
            int n = q.size();
            int[] arr = new int[n], sorted = new int[n];
            for (int i = 0; i < n; i++) {
                var cur = q.poll();
                arr[i] = sorted[i] = cur.val;
                if (cur.left != null) {
                    q.add(cur.left);
                }
                if (cur.right != null) {
                    q.add(cur.right);
                }
            }
            Arrays.sort(sorted);
            HashMap<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < n; i++) {
                map.put(sorted[i], i);
            }
            for (int i = 0; i < n; i++) {
                while (arr[i] != sorted[i]) {
                    int j = map.get(arr[i]);
                    int t = arr[i];
                    arr[i] = arr[j];
                    arr[j] = t;
                    ans++;
                }
            }
        }

        return ans;
    }
}
